package com.aaa.whj.service.impl;

import com.aaa.whj.dao.DeptDao;
import com.aaa.whj.entity.Dept;
import com.aaa.whj.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: whj
 * @Version 1.0
 * @Date: 2022/12/7  15:02
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptDao deptDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /*
    *cacheNames:缓存的名称
    * key: 唯一区分 #id读取方法的参数名的值
     */
    @Override
    @Cacheable(cacheNames="redis::dept",key="#id")
    public Dept selectById(Integer id) {
        /*ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
        //1. 查询缓存: key的名称： 【模块名称::类名::唯一主键】
        Object o = forValue.get("dept::" + id);
        if (o != null){
            return (Dept) o;
        }*/
        Dept dept = deptDao.selectById(id);
        /*if (dept != null){
            //放入缓存以便下次能命中, 缓存中数据会越来越大
            forValue.set("dept::"+id,dept,3600, TimeUnit.SECONDS);
        }*/
        return dept;
    }

    @Override
    @CacheEvict(cacheNames = "redis::dept",key = "#id")
    public Integer delete(Integer id) {
       /* //删除缓存中指定的key
        redisTemplate.delete("dept::"+id);*/
        //只删除了数据库
        int i = deptDao.deleteById(id);

        return i;
    }

    @Override
    public Dept add(Dept dept) {
        deptDao.insert(dept);
        return dept;
    }

    @Override
    @CachePut(cacheNames = "redis::dept",key = "#dept.id")
    public Dept update(Dept dept) {
        //只修改数据库，但是缓存中的数据还是之前的。
        deptDao.updateById(dept);
       /* ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
        forValue.set("dept::"+dept.getId(),dept,3600,TimeUnit.SECONDS);*/
        return dept;
    }
}
